/*
 * $Id$
 *
 * Copyright ( c ) 2014 XuNuo Corporation. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of XuNuo
 * Corporation ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with XuNuo Corporation or a XuNuo
 * authorized reseller (the "License Agreement"). XuNuo may make changes to the
 * Confidential Information from time to time. Such Confidential Information may
 * contain errors.
 *
 * EXCEPT AS EXPLICITLY SET FORTH IN THE LICENSE AGREEMENT, XuNuo DISCLAIMS ALL
 * WARRANTIES, COVENANTS, REPRESENTATIONS, INDEMNITIES, AND GUARANTEES WITH
 * RESPECT TO SOFTWARE AND DOCUMENTATION, WHETHER EXPRESS OR IMPLIED, WRITTEN OR
 * ORAL, STATUTORY OR OTHERWISE INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE. XuNuo DOES NOT WARRANT THAT END USER'S USE OF THE
 * SOFTWARE WILL BE UNINTERRUPTED, ERROR FREE OR SECURE.
 *
 * XuNuo SHALL NOT BE LIABLE TO END USER, OR ANY OTHER PERSON, CORPORATION OR
 * ENTITY FOR INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL
 * DAMAGES, OR DAMAGES FOR LOSS OF PROFITS, REVENUE, DATA OR USE, WHETHER IN AN
 * ACTION IN CONTRACT, TORT OR OTHERWISE, EVEN IF XuNuo HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES. XuNuo' TOTAL LIABILITY TO END USER SHALL NOT
 * EXCEED THE AMOUNTS PAID FOR THE XuNuo SOFTWARE BY END USER DURING THE PRIOR
 * TWELVE (12) MONTHS FROM THE DATE IN WHICH THE CLAIM AROSE.  BECAUSE SOME
 * STATES OR JURISDICTIONS DO NOT ALLOW LIMITATION OR EXCLUSION OF CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO END USER.
 *
 * Copyright version 2.0
 */
package com.th.supcom.pds.phamapply.client.widget.phamapplydetail;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.dict.web.gwt.client.DictComboBox;
import com.th.supcom.framework.dict.web.gwt.client.model.DictModel;
import com.th.supcom.framework.organization.web.gwt.client.model.OrganizationModel;
import com.th.supcom.pds.common.client.commom.SimpleMethod;
import com.th.supcom.pds.common.client.model.CodeConstants;
import com.th.supcom.pds.common.client.widget.PdsGroupGrid;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.phamapply.client.model.InpPhamApplyDetailModel;
import com.th.supcom.pds.phamapply.client.service.InpPhamDispenseDetailRpc;
import com.th.supcom.pds.phamapply.client.service.InpPhamDispenseDetailRpcAsync;

/**
 * 药品请领明细Grid
 * 
 * @author 杨冲
 */
public class PhamApplyDetailGrid extends PdsGroupGrid <InpPhamApplyDetailModel>
{
    private static InpPhamDispenseDetailRpcAsync s_dipenseDetailRpc = GWT.create (InpPhamDispenseDetailRpc.class);

    @Override
    public ColumnModel createColumnModel ()
    {
        List <ColumnConfig> configs = new ArrayList <ColumnConfig> ();
        ColumnConfig column = null;
        column = new ColumnConfig ("color", "", 20);
        column.setRenderer (ClientUtils.getStockEnoughRenderer ());
        configs.add (column);
        column = new ColumnConfig ("repetitionName", "长临", 40);
        configs.add (column);
        column = new ColumnConfig ("orderContent", "医嘱正文", 150);
        configs.add (column);
        column = new ColumnConfig ("dosage", "单次剂量", 60);
        column.setRenderer (getDosageRenerder ());
        configs.add (column);
        column = new ColumnConfig ("scheduleCount", "执行次数", 40);
        column.setRenderer (getScheduleCountRenderer ());
        configs.add (column);
        column = new ColumnConfig ("phamName", "药品名称", 150);
        configs.add (column);
        column = new ColumnConfig ("phamSpec", "规格", 120);
        configs.add (column);
        column = new ColumnConfig ("applyAmount", "数量", 45);
        column.setRenderer (getApplyAmountRenderer ());
        configs.add (column);
        column = new ColumnConfig ("costs", "金额", 50);
        column.setRenderer (getCostsRenderer ());
        column.setAlignment (HorizontalAlignment.RIGHT);
        configs.add (column);
        column = new ColumnConfig ("dispenseResultFlagName", "是否摆药", 50);
        column.setEditor (getDispenseResultFlagCellEditor ());
        configs.add (column);
        column = new ColumnConfig ("administration", "给药途径", 70);
        configs.add (column);
        column = new ColumnConfig ("lastPerformDatetime", "上次截止日期", 60);
        configs.add (column);
        column = new ColumnConfig ("", "执行时间", 60);
        configs.add (column);
        column = new ColumnConfig ("applyDispensaryName", "摆药药房", 100);
        column.setEditor (getDispensaryEditor ());
        configs.add (column);
        column = new ColumnConfig ("destinationName", "送往科室", 100);
        configs.add (column);
        return new ColumnModel (configs);
    }

    /**
     * 获取欠费摆药的
     * 
     * @return
     */
    private CellEditor getDispenseResultFlagCellEditor ()
    {
        DictComboBox arreageDispenseBox = new DictComboBox (CodeConstants.PDS_DISPENSE_RESULT_FLAG);
        arreageDispenseBox.setTriggerAction (TriggerAction.ALL);

        CellEditor editor = new CellEditor (arreageDispenseBox)
        {
            @Override
            public Object preProcessValue (Object value)
            {
                if (null == value)
                {
                    return value;
                }

                BaseModelData data = new BaseModelData ();
                data.set ("dictItemName", value);
                return data;
            }

            @Override
            public Object postProcessValue (Object value)
            {
                if (null == value)
                {
                    return value;
                }
                InpPhamApplyDetailModel model = getGrid ().getSelectionModel ().getSelectedItem ();
                DictModel dictModel = (DictModel) value;
                model.setDispenseResultFlag (dictModel.getDictItemValue ());
                return dictModel.getDictItemName ();
            }
        };
        return editor;
    }

    /**
     * 获取摆药药房CellEditor
     * 
     * @return
     */
    private CellEditor getDispensaryEditor ()
    {
        final ComboBox <OrganizationModel> dispensaryBox = new ComboBox <OrganizationModel> ();
        final ListStore <OrganizationModel> store = new ListStore <OrganizationModel> ();
        dispensaryBox.setStore (store);
        dispensaryBox.setDisplayField ("name");
        dispensaryBox.setTriggerAction (TriggerAction.ALL);
        return new CellEditor (dispensaryBox)
        {
            @Override
            public void startEdit (Element el, Object value)
            {
                InpPhamApplyDetailModel model = getGrid ().getSelectionModel ().getSelectedItem ();
                if (null == model)
                {
                    return;
                }

                s_dipenseDetailRpc.findAvailableDispensary (model.getPhamStdCode (), new AsyncCallback <List <OrganizationModel>> ()
                {

                    @Override
                    public void onSuccess (List <OrganizationModel> result)
                    {
                        store.removeAll ();
                        store.add (result);
                    }

                    @Override
                    public void onFailure (Throwable caught)
                    {
                        MessageBox.alert (CodeConstants.PROMPT, caught.getLocalizedMessage (), null);
                    }
                });
                super.startEdit (el, value);
            }

            @Override
            public Object postProcessValue (Object value)
            {
                if (value == null)
                {
                    return value;
                }
                OrganizationModel model = (OrganizationModel) value;
                getGrid ().getStore ().getAt (super.row).setApplyDispensary (model.getCode ());
                getGrid ().getStore ().getAt (super.row).setApplyDispensaryName (model.getName ());
                getGrid ().getStore ().update (getGrid ().getStore ().getAt (super.row));
                return model.getName ();
            }

            @Override
            public Object preProcessValue (Object value)
            {
                if (value == null)
                {
                    return value;
                }
                OrganizationModel model = new OrganizationModel ();
                model.setName ((String) value);
                return model;
            }
        };
    }

    /**
     * 获取单次剂量的渲染
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getDosageRenerder ()
    {
        return new GridCellRenderer <InpPhamApplyDetailModel> ()
        {

            @Override
            public Object render (InpPhamApplyDetailModel model, String property, ColumnData config, int rowIndex, int colIndex,
                                  ListStore <InpPhamApplyDetailModel> store, Grid <InpPhamApplyDetailModel> grid)
            {
                return model.getDosage () + model.getPhamUnitName ();
            }
        };

    }

    /**
     * 获取执行频率Renderer
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getScheduleCountRenderer ()
    {
        return new GridCellRenderer <InpPhamApplyDetailModel> ()
        {

            @Override
            public Object render (InpPhamApplyDetailModel model, String property, ColumnData config, int rowIndex, int colIndex,
                                  ListStore <InpPhamApplyDetailModel> store, Grid <InpPhamApplyDetailModel> grid)
            {
                return model.getScheduleCount () + "次";
            }
        };
    }

    /**
     * 获取申请数量Renderer
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getApplyAmountRenderer ()
    {
        return new GridCellRenderer <InpPhamApplyDetailModel> ()
        {

            @Override
            public Object render (InpPhamApplyDetailModel model, String property, ColumnData config, int rowIndex, int colIndex,
                                  ListStore <InpPhamApplyDetailModel> store, Grid <InpPhamApplyDetailModel> grid)
            {
                return model.getApplyAmount () + model.getApplyUnitName ();
            }
        };
    }

    /**
     * 获取摆药金额Renderer
     * 
     * @return
     */
    private GridCellRenderer <InpPhamApplyDetailModel> getCostsRenderer ()
    {
        return new GridCellRenderer <InpPhamApplyDetailModel> ()
        {

            @Override
            public Object render (InpPhamApplyDetailModel model, String property, ColumnData config, int rowIndex, int colIndex,
                                  ListStore <InpPhamApplyDetailModel> store, Grid <InpPhamApplyDetailModel> grid)
            {
                // 保留两位小数
                Double cost = SimpleMethod.retainDoubleTwo (model.getCosts ());
                return ClientUtils.formatNumTwo (cost);
            }
        };
    }

    /**
     * 构造函数
     */
    public PhamApplyDetailGrid ()
    {
        getGroupingStore ().groupBy ("paiVisitId");

        GroupingView view = new GroupingView ();
        view.setForceFit (true);
        view.setEmptyText ("暂时没有您需要的数据...");
        view.setShowGroupedColumn (false);
        view.setGroupRenderer (new GridGroupRenderer ()
        {
            public String render (GroupColumnData data)
            {
                Double totalCost = 0D;
                for (ModelData model : data.models)
                {
                    InpPhamApplyDetailModel detailModel = (InpPhamApplyDetailModel) model;
                    totalCost += detailModel.getCosts ();
                }
                totalCost = SimpleMethod.retainDoubleTwo (totalCost);
                return getGroupTitle ((InpPhamApplyDetailModel) data.models.get (0), data.models.size (), totalCost);
            }
        });
        setGridView (view);
    }

    /**
     * 获取分组标题字符串
     * 
     * @return
     */
    private String getGroupTitle (InpPhamApplyDetailModel model, int size, Double totalCost)
    {
        String moneyStr =totalCost.doubleValue ()>model.getBalance ().doubleValue ()?SimpleMethod.moneyStyle (SimpleMethod.retainDoubleTwo (model.getBalance ())):SimpleMethod.retainDoubleTwo (model.getBalance ())+"";
        String totalCostStr = totalCost.doubleValue ()>model.getBalance ().doubleValue ()?SimpleMethod.moneyStyle (totalCost):totalCost+"";
       
        return "床号：" + model.getBedNo () +" 住院号：" + model.getPaiVisitId ()+ " 姓名：" + model.getPaiName () + " 性别：" + model.getGenderName () + " 费别：" + model.getChargeTypeName ()
               + " 预交金余额：" + moneyStr + " 合计：" + totalCostStr + " (" + size + "条明细)";
    }

}
